package code.lib

import scala.xml.{NodeSeq, Text}

import net.liftweb.http.js._
import net.liftweb.util.{CssSel, CanBind}
import net.liftweb.util.BindHelpers._
import net.liftweb.common.{Full, Box}

/**
 * original author: 羊八井
 */
object ExtCssSel {
  private val _selRegex = new scala.util.matching.Regex( """(\S)+""")
  private val _selMatch = Set('*', '-', '[', '^')

  implicit final class YbjStringToCssSel(exp: String) {
    def #>>[T](content: => T)(implicit computer: CanBind[T]): CssSel = {
      val selects = _selRegex.findAllMatchIn(exp).map(_.matched).toList

      val (init, last) =
        if (_selMatch.contains(selects.last.head))
          selects.dropRight(2) -> selects.takeRight(2).mkString(" ")
        else
          selects.dropRight(1) -> selects.takeRight(1).mkString

      init.foldRight(last #> content)((s, c) => s #> c)
    }
  }

  implicit class ExtendedCssSel(sel: CssSel) {
    def &?(another: Box[CssSel]) = {
      another match {
        case Full(cs) => sel & cs
        case _ => sel
      }
    }

    def &?(predAndCS: (Boolean,  CssSel)) = {
      if(predAndCS._1) sel & predAndCS._2
      else sel
    }
  }

}

